package com.xp.basic.heima.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/***
 * 健壮一点的服务端
 * 包含处理客户端断开连接的情况
 */
public class TestStrongSelectorNio {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));
        ssc.configureBlocking(false);

        SelectionKey selectionKey = ssc.register(selector, 0, null);
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);

        while (true){
            System.out.println(" wait connecting ...... ");
            selector.select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                System.out.println("key = " + key);
                iterator.remove();

                if (key.isAcceptable()) {
                    ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                    //接受客户端连接
                    SocketChannel sc = channel.accept();
                    //创建客户端 通道之后设置为非阻塞
                    sc.configureBlocking(false);
                    //将通道注册到 多路复用选择器上面
                    sc.register(selector,SelectionKey.OP_READ);
//                    SelectionKey sck = sc.register(selector, 0, null);
//                    sck.interestOps(SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    try {
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        int read = sc.read(byteBuffer);
                        if (read == -1) {
                            //客户端关闭连接会触发一次 read 事件
                            System.out.println(" 正常关闭客户端连接 ");
                            key.cancel();
                            continue;
                        }
                        System.out.println("read = " + read);
                        byte[] bytes = new byte[read];
                        String msg = new String(bytes);
                        System.out.println(" get client "+ sc +"msg = " + msg);
                    } catch (IOException e) {
                        //客户端关闭连接会触发一次 read 事件 不管是正常关闭还是异常关闭
                        System.err.println("客户端非正常连接关闭 ----"+e.getMessage());
                        key.cancel();
                    }
                }
            }
        }
    }
}
